<template>
  <div class="stomp-container">
    <el-row class="stomp-item" :gutter="20">
      <el-col :span="6">
        <el-button type="primary" @click="sendAuth()">认证</el-button>
      </el-col>
    </el-row>
    <el-row class="stomp-item" :gutter="20">
      <el-col :span="6">
        <el-button type="primary" @click="sendGreeting()">发送</el-button>
      </el-col>
    </el-row>
    <el-row class="stomp-item" :gutter="20">
      <el-col :span="6">
        <el-button type="primary" @click="sendChannel()">
          发送给用户服务
        </el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>

export default {
  name: 'NormWebsocket',
  data() {
    return {
      // path: 'ws://192.168.31.104:8802/bonelf/wst',
      path: 'ws://192.168.31.104:8026/bonelf/wst',
      socket: '',
      header: {
        // authorization: '123'
        authorization: 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MjI2MzU1MzgsInVzZXJfaWQiOjEzMjgyMzE3NTkxOTU3MDk0NDEsImp0aSI6ImQzYThlYmYyLTYxN2EtNDFlMi04ZTEzLWRkZTRhMDU4NmZlZSIsImNsaWVudF9pZCI6ImFwcF9jbGllbnQiLCJzY29wZSI6WyJhcHAiXSwidXNlcm5hbWUiOiIxMzc1ODIzMzAxMSJ9.Js4riLuByuKNA47WrjUpbGMYN_HOaqeUb2nG9JRVDsRtfClQlb7cHZd5OOd6vs3kN7ROkc0OAbqADV2T0GUGiKrBaRxXYiO_tr-K0yJLWZ74rHiDFwCDRgtxb3wI27EXPOmNAjrbMDH9hShh48-7KyaAk5ElUQeI6tt04ny3rtT208CKvhlj6UXNF5wACf4-BEBI_XahBv2jfpF0GtVRGCUpiflH0CCE_HSAz3yyJGYIhgXW_ILKPBi-Dc88OwoDTpVH2ISfMETSBiWKsjQLWhryPVPRKFLraM4ij5ffR0BXsWDm8F1lIEEOpa1bi1TWG8Ume8z6MaUS-UX6hYX-XA'
      }
    }
  },
  computed: {},
  created() {
    this.init()
  },
  methods: {
    sendGreeting() {
      const params = { cmdId: 1, message: 'hello' }
      this.socket.send(JSON.stringify(params))
    },
    sendAuth() {
      const params = { cmdId: 3, message: 'hello', data: this.header }
      this.socket.send(JSON.stringify(params))
    },
    sendChannel() {
      const params = { cmdId: 1, message: 'hello', channel: ['user'] }
      this.socket.send(JSON.stringify(params))
    },
    init: function() {
      if (typeof (WebSocket) === 'undefined') {
        alert('您的浏览器不支持socket')
      } else {
        // 实例化socket
        // this.socket = new WebSocket(this.path + '?authorization=' + this.header.authorization)
        this.socket = new WebSocket(this.path)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    open: function() {
      console.log('socket连接成功')
    },
    error: function() {
      console.log('连接错误')
    },
    getMessage: function(msg) {
      console.log(msg.data)
    },
    close: function() {
      console.log('socket已经关闭')
    }
  }
}
</script>

<style>
.stomp-container {
  padding: 0 50px;
}

.stomp-item {
  margin-top: 50px;
}
</style>
